<template>
  <div>
    <a-row :gutter="18">
      <a-col :span="16">
        <!-- 查询区域 -->
        <a-form layout="inline" class="j-inline-form">
          <!-- 固定条件 -->
          <a-form-item label="长者姓名">
            <a-input placeholder="请输入设备号" v-model="queryParam.deviceId"></a-input>
          </a-form-item>
          <a-form-item label="全选" style="margin-left:8px">
            <a-switch v-model="switchFullscreenDevice" @change="fullUserSwitchDeviceFun"/>
          </a-form-item>
          <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
          <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
        </a-form>

        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
          <i class="anticon anticon-info-circle ant-alert-icon"></i>
          <span style='color:red;font-size: medium' v-if='switchFullscreenDevice'>{{ switchFullscreenTigMsg }}</span>
          已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        </div>

        <a-table
          size="middle"
          bordered
          :rowKey="rowKey"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :scroll="{ y: 240 }"
          :rowSelection="{selectedRowKeys, onChange: onSelectChange, type: multiple ? 'checkbox':'radio'}"
          :customRow="customRowFn"
          @change="handleTableChange">
        </a-table>
      </a-col>
      <a-col :span="8">
        <a-card :title="'已选' + name" :bordered="false" :head-style="{padding:0}" :body-style="{padding:0}">
          <!-- 查询区域 -->
          <a-table size="middle" :rowKey="rowKey" bordered v-bind="selectedTable">
              <span slot="action" slot-scope="text, record, index">
                <a @click="handleDeleteSelected(record, index)">删除</a>
              </span>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
    <a-divider style="margin-bottom: 32px"/>
    <a-form :form="form" style="max-width: 500px; margin: 40px auto 0;">
      <a-form-item :wrapperCol="{span: 19, offset: 5}">
        <a-button :loading="loading" type="primary" @click="nextStep">提交</a-button>
        <a-button style="margin-left: 8px" @click="prevStep">上一步</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
  import CommonUserExtParams from '@views/community/modules/step/CommonUserExtParams'
  import { getAction, postAction, deleteAction, httpAction } from '@api/manage'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { cloneObject, pushIfNotExist } from '@/utils/util'

  export default {
    name: "UserExtStep2",
    mixins: [JeecgListMixin],
    components: {
      CommonUserExtParams,
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        queryParam:{flag:'1'},//TerDeviceInfo.busType
        loading: false,
        switchFullscreenDevice:false,
        switchFullscreenTigMsg:'',
        url: {
          list: '/his/patient/list',
        },
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 5,
          pageSizeOptions: ['5','10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        rowKey:'id',
        multiple:true,
        columns: [
          { title: '长者姓名', align: 'center', dataIndex: 'realName' },
          { title: '性别', align: 'center', width: '20%', dataIndex: 'sex_dictText' },
          { title: '床位号', align: 'center', width: '40%', dataIndex: 'bedInfo' },
        ],
        name:'',
        innerValue: [],
        // 已选择列表
        selectedTable: {
          pagination: false,
          scroll: { y: 240 },
          columns: [
            { title: '长者姓名', align: 'center', width: '50%', dataIndex: 'realName' },
            { title: '操作', dataIndex: 'action', align: 'center', width: 60, scopedSlots: { customRender: 'action' }, }
          ],
          dataSource: [],
        },
      }
    },
    watch: {
      selectedRowKeys: {
        immediate: true,
        deep: true,
        handler(val) {
          if(this.innerValue){
            this.innerValue.length=0;
          }
          this.selectedTable.dataSource = val.map(key => {
            for (let data of this.dataSource) {
              if (data[this.rowKey] === key) {
                pushIfNotExist(this.innerValue, data[this.valueKey])
                return data
              }
            }
            for (let data of this.selectedTable.dataSource) {
              if (data[this.rowKey] === key) {
                pushIfNotExist(this.innerValue, data[this.valueKey])
                return data
              }
            }
            console.warn('未找到选择的行信息，key：' + key)
            return {}
          })
        },
      }
    },
    created() {
      console.log('UserExtStep2 created');
      this.selectedRowKeys = CommonUserExtParams.commonUserExtParamsForm2Data.selectedRowKeys;
      this.selectedTable.dataSource = CommonUserExtParams.commonUserExtParamsForm2Data.dataSource;
    },
    methods: {
      fullUserSwitchDeviceFun(data){
        console.log("fullUserSwitchDeviceFun",data);
        console.log("this.switchFullscreenDevice",this.switchFullscreenDevice);

        if (data){
          this.$message.info("全选模式下，表示已选择所有长者信息！");
          // onClearSelected
          this.selectedRowKeys = [];
          this.selectionRows = [];
          this.switchFullscreenTigMsg='';

          var params = this.getQueryParams();//查询条件
          console.log("params",params);
          getAction(this.url.list, params).then((res) => {
            if (res.success) {
              console.log("res.result.total",res.result.total)
              this.switchFullscreenTigMsg = '全选模式下，按查询条件获取长者信息，本次共有'+res.result.total+'位长者参与活动。';
            }
          })
          this.loadData(1);
        }
      },
      searchQuery() {
        this.queryParam.busType = '0';
        if (this.switchFullscreenDevice){
          this.fullUserSwitchDeviceFun(true);
        }else {
          this.loadData(1, this.value)
        }
      },
      searchReset() {
        this.queryParam = {busType:'0'}
        this.switchFullscreenDevice = false
        this.loadData(1, this.value)
      },
      nextStep () {
        let that = this
        console.log("this.selectedRowKeys:",this.selectedRowKeys)
        console.log("this.selectedTable.dataSource:",this.selectedTable.dataSource)

        let checkRowLen = this.selectedRowKeys.length;
        let dataRowLen = this.selectedTable.dataSource.length;
        let switchFullscreenDevice = this.switchFullscreenDevice;
        console.log("checkRowLen",checkRowLen);
        console.log("dataRowLen",dataRowLen);
        console.log("switchFullscreenDevice",switchFullscreenDevice);
        if (!switchFullscreenDevice && (checkRowLen === 0 || dataRowLen ===0)){
          this.$message.warning("请选择长者信息！");
          return;
        }

        that.loading = true
        CommonUserExtParams.commonUserExtParamsForm2Data = {
          selectedRowKeys : this.selectedRowKeys,
          dataSource : this.selectedTable.dataSource
        }
        console.log(CommonUserExtParams.commonUserExtParamsForm2Data);

        //---- 构建要提交给后台的数据集
        let userIds = [];//人员ID

        let topic = CommonUserExtParams.commonUserExtParamsForm1Data.topic;
        let name = CommonUserExtParams.commonUserExtParamsForm1Data.name;
        let phone = CommonUserExtParams.commonUserExtParamsForm1Data.phone;
        let activityDate = CommonUserExtParams.commonUserExtParamsForm1Data.activityDate;
        let place = CommonUserExtParams.commonUserExtParamsForm1Data.place;
        let organizer = CommonUserExtParams.commonUserExtParamsForm1Data.organizer;
        let organizerId = CommonUserExtParams.commonUserExtParamsForm1Data.organizerId;
        let organizerRole= CommonUserExtParams.commonUserExtParamsForm1Data.organizerRole;
        let doctorId= CommonUserExtParams.commonUserExtParamsForm1Data.doctorId;
        let nurseId= CommonUserExtParams.commonUserExtParamsForm1Data.nurseId;
        let carerId= CommonUserExtParams.commonUserExtParamsForm1Data.carerId;
        let socialWorkerId= CommonUserExtParams.commonUserExtParamsForm1Data.socialWorkerId;

        let userArray = CommonUserExtParams.commonUserExtParamsForm2Data.dataSource;
        for (let i in userArray){
          let po = userArray[i];
          userIds.push(po.id);
        }

        console.log("userIds",userIds);
        console.log("topic",topic);
        console.log("name",name);
        console.log("phone",phone);
        console.log("activityDate",activityDate);
        console.log("place",place);
        console.log("organizer",organizer);

        let userId = userIds.join(",");
        console.log("userId",userId);

        const formData = new FormData();
        formData.append("patientIds",userId);
        formData.append("topic",topic);
        formData.append("name",name);
        formData.append("phone",phone);
        formData.append("activityDate",activityDate);
        formData.append("place",place);
        formData.append("organizer",organizer);
        formData.append("organizerId",organizerId);
        formData.append("organizerRole",organizerRole);
        formData.append("doctorId",doctorId===undefined?"":doctorId);
        formData.append("nurseId",nurseId===undefined?"":nurseId);
        formData.append("carerId",carerId===undefined?"":carerId);
        formData.append("socialWorkerId",socialWorkerId===undefined?"":socialWorkerId);
        console.log("step3表单数据 > ",formData)

        let httpurl = '/his/activity';
        let method = 'post';
        httpAction(httpurl,formData,method).then((res)=>{
          let httpFlag;
          let title;
          let errorMsg;
          if(res.success){
            httpFlag = true;
            title = '操作成功';
            errorMsg = '';
          }else{
            httpFlag = false;
            title = '操作失败';
            errorMsg = res.message;
          }
          CommonUserExtParams.commonUserExtParamsForm3Data.httpFlag = httpFlag;
          CommonUserExtParams.commonUserExtParamsForm3Data.title = title;
          CommonUserExtParams.commonUserExtParamsForm3Data.errorMsg = errorMsg;
        }).finally(() => {
          that.loading = false
          that.$emit('nextStep')
        })
      },
      prevStep () {
        this.$emit('prevStep')
      },
      customRowFn(record) {
        return {
          on: {
            click: () => {
              let key = record[this.rowKey]
              if (!this.multiple) {
                this.selectedRowKeys = [key]
                this.selectedTable.dataSource = [record]
              } else {
                let index = this.selectedRowKeys.indexOf(key)
                if (index === -1) {
                  this.selectedRowKeys.push(key)
                  this.selectedTable.dataSource.push(record)
                } else {
                  this.handleDeleteSelected(record, index)
                }
              }
            }
          }
        }
      },
      /** 删除已选择的 */
      handleDeleteSelected(record, index) {
        this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]), 1)
        //update--begin--autor:wangshuai-----date:20200722------for：JSelectBizComponent组件切换页数值问题------
        this.selectedTable.dataSource.splice(this.selectedTable.dataSource.indexOf(record), 1)
        this.innerValue.splice(this.innerValue.indexOf(record[this.valueKey]), 1)
        console.log("this.selectedRowKeys:",this.selectedRowKeys)
        console.log("this.selectedTable.dataSource:",this.selectedTable.dataSource)
        //update--begin--autor:wangshuai-----date:20200722------for：JSelectBizComponent组件切换页数值问题------
      },
    }
  }
</script>

<style lang="less" scoped>
  .stepFormText {
    margin-bottom: 24px;

    .ant-form-item-label,
    .ant-form-item-control {
      line-height: 22px;
    }
  }
</style>